#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Err.hpp"
#include "log.hpp"

static const int gbacklog = 32;
static const int defaultfd = -1;

class Sock
{
public:
    Sock() : _listensock(defaultfd)
    {
    }
    ~Sock()
    {
    }

    void Socket()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            logmessage(FATAL, "create socket error,code: %d,errstring: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
    }

    void Bind(const uint16_t &port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logmessage(FATAL, "bind error,code: %d,errstring: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listhen()
    {
        if (listen(_listensock, gbacklog) < 0)
        {
            logmessage(FATAL, "listen error,code: %d,errstring: %s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in temp;
        memset(&temp, 0, sizeof(temp));
        socklen_t len = sizeof(temp);
        //std::cout <<"lisen socket fp:"<< _listensock << std::endl;
        int sock = accept(_listensock, (struct sockaddr *)&temp, &len);
        //std::cout<<"accept sucess"<<std::endl;
        if (sock < 0)
        {
            logmessage(WARNING, "listen error,code: %d,errstring: %s", errno, strerror(errno));
        }
        else
        {
            *clientport = ntohs(temp.sin_port);
            *clientip = inet_ntoa(temp.sin_addr);
        }
        return sock;
    }

    int Connect(std::string &serverip, uint16_t &serverport)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(serverip.c_str());
        server.sin_port = htons(serverport);

        int n = connect(_listensock, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            logmessage(WARNING, "connect error,code: %d,errstring: %s", errno, strerror(errno));
            exit(CONNECT_ERR);
        }
        return n;
    }

    void Close()
    {
        if (_listensock != defaultfd)
            close(_listensock);
    }

    int Fd()
    {
        return _listensock;
    }

private:
    int _listensock;
};
